//
//  GFMapTableViewCell.m
//  GoodFood
//
//  Created by dllo on 15/10/30.
//  Copyright © 2015年 荣伟峰. All rights reserved.
//

#import "GFMapTableViewCell.h"

@interface GFMapTableViewCell ()<BMKMapViewDelegate, BMKLocationServiceDelegate>
@property (nonatomic, strong) BMKMapView *mapView;
@property (nonatomic, strong) BMKLocationService *locationService;
@property (nonatomic, strong) UIView *viewForExit;//退出放大地图的view
@property (nonatomic, strong) UILabel *labelForExit;//退出放大地图状态的label
@property (nonatomic, assign) BOOL status;//手势状态开关
@property (nonatomic, strong) UIView *viewForMap;
@property (nonatomic, strong) UILabel *addressLabel;
@property (nonatomic, strong) NSMutableArray *annotations;
@property (nonatomic, assign) BOOL isExist;
@end

@implementation GFMapTableViewCell

#pragma mark - 初始化
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        
        [self.mapView viewWillAppear];
        [self creatView];
        [self creatMap];
        [self tap];
        [self creatLabel];
    }
    return self;
}

#pragma mark - 布局
- (void)layoutSubviews {
    [super layoutSubviews];

    self.viewForMap.frame = CGRectMake(self.contentView.frame.size.width / 15, 0, ScreenWidth - self.contentView.frame.size.width / 15 * 2, self.contentView.frame.size.height);
    self.mapView.frame = CGRectMake(0, 0, self.viewForMap.frame.size.width,self.contentView.frame.size.height / 1.25);
    
    CGRect rectForAddress = [self.model.address boundingRectWithSize:CGSizeMake(self.viewForMap.frame.size.width, self.contentView.frame.size.height - self.contentView.frame.size.height / 1.25) options:1 attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12]} context:nil];
    self.addressLabel.frame = CGRectMake(0, self.contentView.frame.size.height / 1.25, rectForAddress.size.width, rectForAddress.size.height);
    self.viewForMap.frame = CGRectMake(self.contentView.frame.size.width / 15, 0, ScreenWidth - self.contentView.frame.size.width / 15 * 2, self.contentView.frame.size.height / 1.25 + rectForAddress.size.height);
}
#pragma mark - set
- (void)setModel:(GFResturtantDetialModel *)model {
    if (_model != model) {
        _model = model;
    }
    [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(model.place_geo_lat, model.place_geo_lng)];
    //大头针的信息
    if ((!self.isExist)&& model) {
        self.annotations = [NSMutableArray array];
        BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
        CLLocationCoordinate2D pt = CLLocationCoordinate2DMake(model.place_geo_lat, model.place_geo_lng);
        item.coordinate = pt;
        item.title = model.place_name;
        [self.annotations addObject:item];
        [self.mapView addAnnotations:self.annotations];
        [self.mapView showAnnotations:self.annotations animated:1];
        self.isExist = YES;
    }
    if (model.place_geo_lng == 0 || model.place_geo_lat == 0) {
        self.mapView.delegate = nil;
        [self.mapView removeFromSuperview];
        [self.addressLabel removeFromSuperview];
        [self.viewForMap removeFromSuperview];
    } else {
        self.mapView.delegate = self;
        [self.viewForMap addSubview:self.mapView];
        [self.viewForMap addSubview:self.addressLabel];
        [self.contentView addSubview:self.viewForMap];
    }

    //地址
    self.addressLabel.text = model.address;
}
#pragma mark - 创建地图
- (void)creatMap {
    
    self.mapView = [[BMKMapView alloc] init];
    self.locationService = [[BMKLocationService alloc] init];
    
    self.locationService.delegate = self;
    [self.mapView setZoomLevel:13];
    self.mapView.scrollEnabled = NO;
    [self.mapView setZoomEnabled:NO];
    [self.mapView setRotateEnabled:NO];
    //定位
    [self.locationService startUserLocationService];
    self.mapView.showsUserLocation = NO;
    self.mapView.userTrackingMode = BMKUserTrackingModeNone;
    self.mapView.showsUserLocation = YES;
}
#pragma mark - 定位代理
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation {
    NSLog(@"%f",userLocation.location.coordinate.latitude);
    if (userLocation.location.coordinate.latitude != 0 && userLocation.location.coordinate.longitude != 0) {

        [self.mapView updateLocationData:userLocation];
        [self.locationService stopUserLocationService];
    }
}
#pragma mark - 定位结束
- (void)didStopLocatingUser {
    
    self.locationService.delegate = nil;
}
#pragma mark - 创建view
- (void)creatView {
    self.viewForExit = [[UIView alloc] init];
    self.viewForExit.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
    
    self.viewForMap = [[UIView alloc] init];
    self.viewForMap.layer.masksToBounds = YES;
    self.viewForMap.layer.cornerRadius = 5;
    self.viewForMap.layer.borderWidth = 0.3;
    self.viewForMap.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.viewForMap.layer.shadowColor = [UIColor blueColor].CGColor;
    self.viewForMap.layer.shadowOffset = CGSizeMake(10, 100);
    self.viewForMap.layer.shadowRadius = 10;
    
}
#pragma mark - 创建label
- (void)creatLabel {
    self.labelForExit = [[UILabel alloc] init];
    self.labelForExit.text = @"请长按2秒退出地图";
    self.labelForExit.font = [UIFont systemFontOfSize:13];
    self.labelForExit.textColor = [UIColor whiteColor];
    self.labelForExit.frame = CGRectMake(0, 0, ScreenWidth / 3, ScreenHeight / 40);
    [self.viewForExit addSubview:self.labelForExit];
    
    self.addressLabel = [[UILabel alloc] init];
    self.addressLabel.font = [UIFont systemFontOfSize:12];
    self.addressLabel.numberOfLines = 0;
    
    
}
#pragma mark - key动画
- (void)keyAnimationForLabel {
    CAKeyframeAnimation *keyFrame = [CAKeyframeAnimation animationWithKeyPath:@"position"];
  
    CGMutablePathRef path = CGPathCreateMutable();
    
    CGPathMoveToPoint(path, NULL, ScreenWidth, self.labelForExit.center.y);
    
    CGPathAddLineToPoint(path, NULL,0 - self.labelForExit.frame.size.width, self.labelForExit.center.y);
   
    keyFrame.path = path;
   
    keyFrame.duration = 5;
    keyFrame.autoreverses = 0;
    keyFrame.repeatCount = CGFLOAT_MAX;
    
    [self.labelForExit.layer addAnimation:keyFrame forKey:@"key"];
}
#pragma mark - basic动画
- (void)basicAnimation {
    CABasicAnimation *basic = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    if (self.status) {
        basic.fromValue = [NSNumber numberWithInt:0];
        basic.toValue = [NSNumber numberWithFloat:1];
    } else {
        basic.fromValue = [NSNumber numberWithInt:1];
        basic.toValue = [NSNumber numberWithFloat:0.3];
    }

  
    basic.duration = 0.5;
    basic.autoreverses = 0;
    basic.repeatCount = 0;
    
    [self.mapView.layer addAnimation:basic forKey:@"basic"];
}
#pragma mark - tran动画
- (void)tranAnimation {
    CATransition *transition = [CATransition animation];
    /* 2.设置type类型 */
    transition.type = kCATransitionFade;
    /* 3.设置动画属性 */
    transition.duration = 0.5;
    transition.autoreverses = 0;
    
    transition.repeatCount = 1;
    /* 4.layer添加动画 */
    [self.mapView.layer addAnimation:transition forKey:@"trans"];
}
#pragma mark - 画大头针
- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation
{
    // 生成重用标示identifier
    NSString *AnnotationViewID = @"addressMark";
    
    // 检查是否有重用的缓存
    BMKAnnotationView* annotationView = [view dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    // 缓存没有命中，自己构造一个，一般首次添加annotation代码会运行到此处
    if (annotationView == nil) {
        annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        ((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorRed;
        // 设置重天上掉下的效果(annotation)
        ((BMKPinAnnotationView*)annotationView).animatesDrop = NO;
    }
    
    // 设置位置
    annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
    annotationView.annotation = annotation;
    // 单击弹出泡泡，弹出泡泡前提annotation必须实现title属性
    annotationView.canShowCallout = YES;
    // 设置是否可以拖拽
    annotationView.draggable = NO;
    
    return annotationView;
}
- (void)awakeFromNib {
    // Initialization code
}
#pragma mark - 地图轻拍手势
- (void)tap {
    UITapGestureRecognizer *tapG = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
    tapG.numberOfTapsRequired = 1;
    tapG.numberOfTouchesRequired = 1;
    [self.mapView addGestureRecognizer:tapG];

}
- (void)tap:(UITapGestureRecognizer *)tap {
    self.status = YES;
    self.viewForMap.layer.borderWidth = 0;
    UIViewController *vc= [self viewController];
    [self.mapView removeFromSuperview];
    [vc.view addSubview:self.mapView];
    self.mapView.scrollEnabled = YES;
    [self.mapView setZoomEnabled:YES];
    [self.mapView setRotateEnabled:YES];
    self.mapView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    [self basicAnimation];
    [self performSelector:@selector(timeDelay) withObject:nil afterDelay:0.5];
    [self.mapView removeGestureRecognizer:tap];
    
// [self.contentView.superview addSubview:self.bigView];

}
#pragma mark - 时间延迟
- (void)timeDelay {
    UIViewController *vc= [self viewController];
    UIView *view = (UIView *)[vc.navigationController.view viewWithTag:10001];
    if (self.status) {
        view.hidden = YES;
        vc.navigationController.navigationBarHidden = YES;
        self.viewForExit.frame = CGRectMake(0, 20, ScreenWidth, ScreenHeight / 40);
        [vc.view addSubview:self.viewForExit];
        [self keyAnimationForLabel];
        [self longPress];
    } else {
        [self.viewForExit removeFromSuperview];
        view.hidden = NO;
        vc.navigationController.navigationBarHidden = NO;
        self.viewForMap.layer.borderWidth = 0.3;
        [self tap];
    }

}
#pragma mark - 长按手势
- (void)longPress {
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    [longPress setMinimumPressDuration:0.8];
    [self.mapView addGestureRecognizer:longPress];
}
- (void)longPress:(UILongPressGestureRecognizer *)longPress {
    if ([longPress state] == UIGestureRecognizerStateBegan) {
        self.status = NO;
        [self.mapView removeFromSuperview];
        self.mapView.frame = CGRectMake(0, 0, self.viewForMap.frame.size.width,self.contentView.frame.size.height / 1.25);
        [self basicAnimation];
        [self.viewForMap addSubview:self.mapView];
        self.mapView.scrollEnabled = NO;
        [self.mapView setZoomEnabled:NO];
        [self.mapView setRotateEnabled:NO];
        [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(self.model.place_geo_lat, self.model.place_geo_lng)];
        [self.mapView setZoomLevel:13];
        [self performSelector:@selector(timeDelay) withObject:nil afterDelay:0.5];
    }
}
#pragma mark - 找到vc
- (UIViewController*)viewController {
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
